import { MutableRefObject } from 'react';
import { Field } from '@formily/core';
import { IPageInbiz } from '@inbiz/core/lib/sdk/inbiz';
import { SearchParamsProps } from './context';
import formatters from './formatters';
import { ConditionsType, PageData } from './interfaces';
import { MemberTypeKeyMap, objIsNotEmpty } from './shared';

/**
 * 查找表格是否在弹框内
 */
const isTableInModal: (el: HTMLElement | null) => any = (el: HTMLElement | null) => {
  // 传入标签是否是DOM对象
  if (!(el instanceof HTMLElement)) return false;
  if (el && el.parentElement?.nodeName == 'BODY') return false;
  if (el && el.parentNode?.className.includes('ant-modal-body')) {
    return true;
  }
  return isTableInModal(el?.parentElement);
};

/**
 * 获取屏幕高度、表格的body到外层容器的高度、表头高度、分页高度、弹框高度
 */
const getHeights = (params: {
  controlId: string;
  maxHeight: { suffix: string };
  showPage: boolean | undefined;
}) => {
  const { controlId, maxHeight, showPage } = params;
  let windowHeight = window.innerHeight;
  let paginationHeight = 52;
  const table: any = document.querySelector(`#${controlId}zebra .ant-table`);
  const tableHeader: number =
    document.querySelector(`#${controlId}zebra .ant-table-header`)?.clientHeight || 48;
  const inModal = isTableInModal(table);
  // 判断表格是否存在于弹框中
  if (inModal) {
    const loadPageModal = document.querySelector('.ant-modal.loadpage'); // loadPage打开的弹框
    const { suffix } = maxHeight;
    const modalMaxHeight = document.querySelector('.ant-modal')?.style?.maxHeight;
    const modalHeader = document.querySelector('.ant-modal-header')?.clientHeight || 0;
    const modalBody = document.querySelector('.ant-modal-body');
    const { paddingTop, paddingBottom } = getComputedStyle(modalBody!);
    const modalBodyPadding = parseFloat(paddingTop) + parseFloat(paddingBottom);
    const modalFooter = document.querySelector('.ant-modal-footer')?.clientHeight || 0;
    if (loadPageModal) {
      const loadPageHeight = document.querySelector('.ant-modal.loadpage')?.clientHeight || 0;
      windowHeight = loadPageHeight - modalHeader - modalFooter - modalBodyPadding;
    } else {
      if (suffix == '%') {
        windowHeight =
          windowHeight * (parseFloat(modalMaxHeight) / 100) -
          modalHeader -
          modalFooter -
          modalBodyPadding;
      } else {
        windowHeight = parseFloat(modalMaxHeight) - modalHeader - modalFooter - modalBodyPadding;
      }
    }
  }
  // 首次渲染表格，分页的dom可能会获取不到，需特殊处理，以便获取分页组件的实际高度
  if (showPage) {
    const pagin = document.querySelector(`#${controlId}zebra .ant-table-pagination`);
    if (pagin) {
      const pagination = getComputedStyle(pagin!);
      const { height } = pagination;
      paginationHeight = parseFloat(height);
    }
  }
  return {
    windowHeight,
    paginationHeight,
    tableHeader,
  };
};

/**
 * 移除分页的next标签title属性；根据表格是否有数据，动态设置高度
 */
const setTableBodyHeight = (params: {
  inbizTableRef: MutableRefObject<any>;
  tableHeight: number | undefined;
  pageData: PageData;
  showHeightRule: string | undefined;
}) => {
  const { inbizTableRef, tableHeight = 0, pageData, showHeightRule } = params;
  if (!inbizTableRef?.current) {
    return false;
  }
  const pagin = inbizTableRef.current.querySelector('.ant-pagination-next');
  pagin?.removeAttribute('title');
  const isDisabled = pagin?.getAttribute('aria-disabled');
  const tableBody: any = inbizTableRef.current.querySelector('.ant-table-body');
  const tableBodyLayout: any = inbizTableRef.current.querySelector('.ant-table-body table');
  // 判断表格是否有数据
  if (!pageData?.data?.length && showHeightRule == 'fixed') {
    tableBody.style.height = `${tableHeight + 20}px`;
    tableBody.style.maxHeight = `${tableHeight + 20}px`;
    // 撑满可用空间
    tableBodyLayout.style.height = '-webkit-fill-available';
  } else {
    tableBody.style.height = 'auto';
    tableBody.style.maxHeight = `${tableHeight - 20}px`;
    tableBodyLayout.style.height = 'auto';
  }
  return isDisabled;
};

/**
 * 树结构扁平化
 */
const treeToArray = (tree: { [key: string]: any }[]) => {
  let data: { [key: string]: any }[] = [];
  for (const item of tree) {
    const { children, ...rest } = item;
    if (children && children?.length) {
      data = data.concat(treeToArray(children));
    } else {
      data.push(rest);
    }
  }
  return data;
};

/**
 * 获取查询区域组件的值
 */
const getSearchValues = (params: {
  isSaveSearch?: boolean;
  inbiz: IPageInbiz;
  controlId?: string;
  searchRef: React.MutableRefObject<SearchParamsProps>;
  queryFields: {
    value: string | number;
    label: string;
  }[];
  initCondition?: any
  components?: Field[];
}) => {
  const { isSaveSearch = false, inbiz, controlId, searchRef, queryFields, initCondition, components } = params;
  const values = {};
  const _components = components || (inbiz as any)?.getFields?.(controlId);
  _components?.forEach((field: Field) => {
    if (components?.length) {
      values[field.componentProps.controlId] = {
        value:
          field?.componentType === 'EformMemberSelect'
            ? field?.value?.map((value: any) =>
              formatters.formatMemberSelectValue(value, field?.componentProps?.tabs),
            )
            : field?.value,
        type: field?.componentType,
        name: field.props.name,
      };
    } else {
      if (field.hasOwnProperty('value') && field?.componentProps?.tablequeryfield) {
        // 成员选择查询时需要格式化查询数据
        values[field?.componentProps?.tablequeryfield] = {
          value:
            field?.componentType === 'EformMemberSelect'
              ? field?.value?.map((value: any) =>
                formatters.formatMemberSelectValue(value, field?.componentProps?.tabs),
              )
              : field?.value,
          type: field?.componentType,
          name: field.props.name,
        };
      }
    }
  });
  const initParams = searchRef.current.initParams;
  const searchValues =
    objIsNotEmpty(values) && queryFields
      ? formatters.getQueryGroups(queryFields, values, initParams)
      : [];
  if (initCondition) {
    searchValues.push(initCondition);
  }
  if (!isSaveSearch) {
    searchRef.current = {
      ...searchRef.current,
      pageInfo: {
        ...searchRef.current.pageInfo!,
        current: 1,
      },
      conditions: searchValues,
      iConditions: {
        ...searchRef.current.iConditions,
        pageIndex: 1
      }
    };
  }
  return searchValues;
};

/**
 * 查询组件回显数据
 */
const setComponentsValue = (params: {
  ComponentValues: ConditionsType[] | undefined;
  inbiz: Function;
}) => {
  const { ComponentValues = [], inbiz } = params;
  // 临时处理成员选择组件调用setValueToID方法，因该方法异步，导致查询时无法获取数据
  let menber = null;
  ComponentValues.forEach((item) => {
    if (inbiz && inbiz(item.condition?.[0]?.name)) {
      const { componentType, multiple } = inbiz(item.condition?.[0]?.name);
      // 成员选择要单独处理
      if (componentType == 'EformMemberSelect') {
        // 获取成员选择的配置，tabs长度为1，代表的是单选标签，其他情况均为多选
        const { tabs = [], multiple  } = inbiz(item.condition[0].name);
        const isMulti = tabs.filter(tab => !tab?.hide)?.length == 1;
        // condition长度大于1代表是多选
        if (multiple) {
          const values = item.condition.map((item: { value: string }) => {
            const [type, id] = item.value.split(':');
            return {
              memberType: isMulti ? '0' : MemberTypeKeyMap[type],
              memberIds: isMulti ? [item.value] : [id],
            };
          });
          if (inbiz(item.condition[0].name)?.setValueToID) {
            inbiz(item.condition[0].name)?.setValueToID?.(values);
          } else {
            inbiz(item.condition[0].name).on('mount', () => {
              inbiz(item.condition[0].name)?.setValueToID?.(values);
            })
          }
        } else {
          const [type, id] = item.condition[0].value.split(':');
          if (inbiz(item.condition[0].name)?.setValueToID) {
            inbiz(item.condition[0].name)?.setValueToID?.({
              memberType: isMulti ? '0' : MemberTypeKeyMap[type],
              memberIds: isMulti ? [item.condition[0].value] : [id],
            });
          } else {
            inbiz(item.condition[0].name).on('mount', () => {
              inbiz(item.condition[0].name)?.setValueToID?.({
                memberType: isMulti ? '0' : MemberTypeKeyMap[type],
                memberIds: isMulti ? [item.condition[0].value] : [id],
              });
            })
          }
          
        }
        menber = item;
      } else {
        // 级联组件需单独处理
        const isCascader = componentType === 'Cascader';
        // condition长度大于1代表是多选
        if (item.condition.length > 1) {
          const values = item.condition.map((item: { value: string }) => {
            if (isCascader) {
              // 如果是级联组件，回显时需要格式化value，转为数组后，只取最后一项(选中项的id)
              const valueArr = item.value.split(',');
              return valueArr[valueArr.length - 1]
            }
            return item.value
          });
          inbiz(item.condition[0].name).value = values;
        } else {
          let value = item.condition[0].value;
          if (isCascader) {
            // 如果是级联组件，回显时需要格式化value，转为数组后，只取最后一项(选中项的id)
            const valueArr = value.split(',');
            value = multiple ? [valueArr[valueArr.length - 1]] : valueArr[valueArr.length - 1];
          }
          inbiz(item.condition[0].name).value = value;
        }
      }
    }
  });
  return menber;
}

export { getHeights, setTableBodyHeight, treeToArray, getSearchValues, isTableInModal, setComponentsValue };
